package com.bjtu.ptsite.controller;

import bt.Bt;
import bt.runtime.BtClient;

import com.bjtu.ptsite.model.PageResult;
import com.bjtu.ptsite.model.Result;
import com.bjtu.ptsite.model.User;
import com.bjtu.ptsite.tracker.entity.TorrentEntity;
import com.bjtu.ptsite.tracker.entity.TrackerMessage;
import com.bjtu.ptsite.tracker.entity.TrackerRequest;
import com.bjtu.ptsite.tracker.service.TrackerService;
import com.bjtu.ptsite.utils.RequestUtil;

import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Zehao Wang, Junjie Zhang, Yutao Wei
 *
 */
@CrossOrigin
@Slf4j
@RestController
@RequestMapping("/tracker")
public class TrackerController {

    /**
     * 用户上传文件 bt 种子 转torrent->存到数据库以及tracker-> 用户进行下载
     */
    @Autowired
    private TrackerService trackerService;

    @ApiOperation("创建种子")
    @PostMapping("/createTorrent")
    public Result createTorrent(@RequestParam("title") String title,
            @RequestParam("description") String description,
            @RequestParam("categoryId") Integer categoryId,
            @RequestParam("isAnonymous") boolean isAnonymous,
            @RequestParam("isFreeleech") boolean isFreeleech,
            @RequestPart("torrentFile") MultipartFile torrentFile) {
        TrackerRequest param = new TrackerRequest();
        param.setTitle(title);
        param.setDescription(description);
        param.setCategoryId(categoryId);
        param.setAnonymous(isAnonymous);
        param.setFreeleech(isFreeleech);
        log.info("createTorrent: {}", param);
        if (param == null) {
            return Result.error("参数错误");
        }

        return Result.success(trackerService.createTorrent(param, torrentFile));
    }

    @ApiOperation("用户上传种子")
    @PostMapping("/uploadTorrent")
    public Result uploadTorrent(@RequestParam("title") String title,
            @RequestParam("description") String description,
            @RequestParam("categoryId") Integer categoryId,
            @RequestParam("isAnonymous") boolean isAnonymous,
            @RequestParam("isFreeleech") boolean isFreeleech,
            @RequestPart("torrentFile") MultipartFile torrentFile) {
        TrackerRequest param = new TrackerRequest();
        param.setTitle(title);
        param.setDescription(description);
        param.setCategoryId(categoryId);
        param.setAnonymous(isAnonymous);
        param.setFreeleech(isFreeleech);

        log.info("uploadTorrent: {}", param);
        if (torrentFile.isEmpty() || torrentFile == null) {
            return Result.error("torrentFile 不能为空");
        }
        param.setTorrentFile(torrentFile);
        // todo 后面改为异步
        boolean flag = false;
        long l = System.currentTimeMillis();
        flag = trackerService.uploadTorrent(param);
        long l1 = System.currentTimeMillis();
        log.info("uploadTorrent time: {}", l1 - l);
        return Result.success(flag);
    }

    @ApiOperation("获取磁力链接")
    @GetMapping("/getMagnet")
    public Result getMagnet(@RequestBody TrackerRequest param) {

        log.info("getMagnet: {}", param.getId());
        if (param.getId() == null) {
            return Result.error("TrackerMessage id不能为空");
        }

        return trackerService.getMagnet(param);
    }

    @ApiOperation("下载")
    @PostMapping("/downloadTorrent")
    public Result download(@RequestBody TrackerRequest param) {

        log.info("getMagnet: {}", param.getId());
        if (param.getId() == null) {
            return Result.error("TrackerMessage id不能为空");
        }

        String url = trackerService.downloadTorrent(param, param.getPassKey());

        return Result.success(url);
    }

    @ApiOperation("连接性检测")
    @PostMapping("/isConnect")
    public Result isConnect(@RequestBody TrackerRequest param) {

        log.info("isConnect: {}", param.getId());
        if (param.getId() == null) {
            return Result.error("TrackerMessage id不能为空");
        }

        boolean flag  = trackerService.isConnect(param);
        return Result.success(flag);
    }

    @ApiOperation("获取种子列表")
    @PostMapping("/getTorrentList")
    public Result getTorrentList(@RequestBody TorrentEntity torrentEntity,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer categoryId) {
        if (torrentEntity.getId() != null) {
            TrackerMessage trackerMessage = trackerService.getSpTorrent(torrentEntity.getId());
            return Result.success(trackerMessage);
        }
        log.info("getTorrentList request with category: {}", categoryId);
        PageResult<TrackerMessage> result = trackerService.getTorrentList(page, size, categoryId);
        return Result.success(result);
    }

    @ApiOperation("获取某人种子列表(包括自己)")
    @GetMapping("/getUserTorrentList/{userId}")
    public Result getUserTorrentList(@PathVariable int userId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer categoryId) {
        int myId = RequestUtil.getUserContext().getId();
        int flag = (myId == userId) ? 0 : 1;
        PageResult<TrackerMessage> result = trackerService.getUserTorrentList(flag, userId, page, size, categoryId);
        if (result.getTotal() == 0) {
            return Result.error("他/她没有发布种子");
        }
        return Result.success(result);
    }

    @ApiOperation("获取注册种子列表")
    @PostMapping("/getResgitedTorrentList")
    public Result getResgitedTorrentList() throws IOException {

        boolean flag = trackerService.dumpRegisteredTorrents();

        return Result.success(flag);

    }

    @ApiOperation("获取种子peers")
    @GetMapping("/listPeers")
    public Result listPeers(@RequestParam String infoHash) {
        if (infoHash == null) {
            return Result.error("infoHash不能为空");
        }
        List<Map<String, Object>> peerInfoList = trackerService.listPeers(infoHash);

        return Result.success(peerInfoList);
    }

}
